<template>
  <div class="personnel_body">
    <div class="personnel_header">
      <div class="personnel_header_title">{{ organization.name }}</div>
      <div class="personnel_header_subheading">提供员工的联系方式和所在部门</div>
    </div>
    <div class="personnelList">
      <div class="roleTree">
        <div class="tree_search">
          <el-input v-model="treeText" size="mini" @input="enterInput" placeholder="请输入部门搜索" />
        </div>
        <div class="tree_body">
          <el-tree :indent="5" :default-expand-all="true" :data="companyData" ref="treeRef" node-key="id"
            :current-node-key="0" :props="defaultProps" :highlight-current="true" :expand-on-click-node="false"
            :filter-node-method="filterNode" @node-click="handleNodeClick">
            <template #default="{ node }">
              <div class="custom-tree-node">
                <div :class="[settingClass(node)]" v-if="node.level === 1" style="font-size: 14px;width: 100%">{{
                  node.label }}</div>
                <div :class="[settingClass(node)]" v-else style="font-size: 14px">{{ node.label }}</div>
              </div>
            </template>
          </el-tree>
        </div>
      </div>
      <div class="personnelList_div">
        <div class="personnelList_div_body" ref="personnelListDivBody">
          <div>
            <div class="personnel_search" ref="personnelSearch">
              <el-form :inline="true" size="large" :model="formInline" class="demo-form-inline">
                <el-form-item>
                  <el-radio-group v-model="formInline.status">
                    <el-radio-button :label="false">未移除</el-radio-button>
                    <el-radio-button :label="true">已移除</el-radio-button>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="关键字：">
                  <el-input v-model="formInline.user" placeholder="请输入姓名" clearable />
                </el-form-item>
              </el-form>
            </div>
            <div class="personnel_list_body" :style="{ height: tableHeight + 'px' }">
              <div class="personnel_list_body_left">
                <div class="personnel_list">
                  <template>
                    <div v-for="(data, index) in tableData" :key="index">

                      <el-popover placement="right" width="200" trigger="click">
                        <div class="operate">
                          <div class="one_operate" @click="editPersonnel(data)">详情</div>
                          <div class="one_operate" v-if='data.removed' @click="beReinstated(data)">复任</div>
                          <div class="one_operate" v-else @click="leaveOffice(data)">离职</div>
                        </div>
                        <div class="onePersonnel" slot="reference"
                          :class="[data.isMale ? 'onePersonnel_man' : 'onePersonnel_woman']" :key="index">
                          <!--                        <div class="onePersonnel_img">-->
                          <!--                          <img v-if="data.isMale" src="@/assets/man.png" alt="">-->
                          <!--                          <img v-else src="@/assets/woman.png" alt="">-->
                          <!--                        </div>-->
                          <div class="personnel_content">
                            <div class="personnel_content_li">
                              姓名：{{ data.name }}
                              <span v-if="data.isAdmin" style="color: red;font-weight: bold">(管理员)</span>
                            </div>
                            <!--                          <div class="personnel_content_li">职务：{{ postList[data.officialRank] }}</div>-->
                            <div class="personnel_content_li">所属部门：{{ data.department ? data.department.name : '无' }}
                            </div>
                          </div>
                          <div class="onePersonnel_bg"></div>
                        </div>
                      </el-popover>
                    </div>
                  </template>
                </div>
              </div>
              <div class="personnel_list_body_right">
                <div class="oneLetter" v-for="(data, index) in letterArr" :key="index">{{ data }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="operate_div">
        <div class="operate_div_body">
          <div>新增人员</div>
          <div style="font-size: 14px;line-height:1.5;color: #ababab;margin-bottom: 15px">新增人员</div>
          <el-button type="primary" size="large" style="width: 100%;margin-bottom: 20px" @click="addPersonnelFun()">
            新增人员
          </el-button>
          <div>单位</div>
          <div style="font-size: 14px;line-height:1.5;color: #ababab;margin-bottom: 15px">快速预览部门组织架构</div>
          <el-button type="primary" size="large" style="width: 100%" @click="goOrganizational()">
            组织架构
          </el-button>
        </div>
      </div>
    </div>
    <addPersonnel @updateData="getTableData" v-model="showAdd" :departments="departments"></addPersonnel>
  </div>
</template>

<script>
import addPersonnel from "@/components/addPersonnel/index.vue";
export default {
  name: 'userList',
  components: {
    addPersonnel
  },
  data() {
    return {
      showAdd: false,
      department: [],
      holdersWithEmployee: [],
      letterArr: [
        'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', "J", 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
      ],
      tableHeight: 0,
      treeText: null,
      treeRef: null,
      formInline: {
        status: false,
        userName: null,
        department: null,
        post: null
      },
      defaultProps: {
        children: 'children',
        label: 'name',
      },
      organization: {
        name: ''
      },
      tableData: [],

      companyData: [],
      departments: [],
      postList: {
        NONE: '无',
        ADMINSTRATOR: '负责人',
        DIRECTOR: '主管',
        WOKER: '干事',
      },
      departmentType: {},
    }
  },
  computed: {
    userInfo() {
      return this.$store.state.userInfo
    },
    employeeInfo() {
      return this.$store.state.employeeInfo
    },
  },
  methods: {

    enterInput() {
      this.$refs.treeRef.filter(this.treeText)
    },
    goOrganizational() {
      this.$router.push('/organizational')
    },
    filterNode(value, data) {
      if (!value) return true
      return data.name.includes(value)
    },
    getTableHeight() {
      this.$nextTick(() => {
        this.tableHeight = this.$refs.personnelListDivBody.clientHeight - this.$refs.personnelSearch.clientHeight - 20
      })
    },
    addPersonnelFun() {
      this.showAdd = true
    },
    editPersonnelFun(data) {
      this.$router.push(`/editPersonnel?id=${data.id}`)
    },
    settingClass(node) {
      return node.level === 3 ? 'childCLass' : node.level === 2 ? 'parentClass' : ''
    },
    handleNodeClick(data) {
      this.tableData = data.employees
    },
    beReinstated(data) {
      this.$confirm('确定是否办理复任?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.beReinstatedFun(data)
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => { });
    },
    editPersonnel(data) {
      this.$router.push(`/editPersonnel?id=${data.id}`)
    },
    async beReinstatedFun(data) {
      console.log(data)
      const res = await this.$axios.post('/graphql', {
        query: `mutation {
          employeeManagementScene {
            goBack(id: "string", organId: "string", deptId: "string", officalRank: NONE)
          }
        }`
      })
      if (res.data.errors) {
        this.$message.error(res.data.errors[0].message)
      } else {
        this.$message.success('已离职');
        this.getTableData()
      }
    },
    leaveOffice(data) {
      this.$confirm('确定是否办理离职?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.leaveOfficeFun(data)
      }).catch(() => { });
    },
    async leaveOfficeFun(data) {
      const res = await this.$axios.post('/graphql', {
        query: `mutation {
          employeeManagementScene {
            leaveOffice(id: "${data.id}")
          }
        }`
      })
      if (res.data.errors) {
        this.$message.error(res.data.errors[0].message)
      } else {
        this.$message.success('已离职');
        this.getTableData()
      }
    },
    async getTableData() {
      console.log(this.holdersWithEmployee)
      const holdersWithEmployeeId = this.holdersWithEmployee.map(item => {
        return item.id
      })
      const res = await this.$axios.post('/graphql', {
        query: `{
        organizationQueryRepository {
          findById(id: "${this.employeeInfo.organization.id}") {
            id
            removed
            uniqueCode
            name
            shortName
            employees {
              getItems {
                id
                name
                pinyin
                phoneNumber
                officialRank
                isMale
                removed
                department {
                  id
                  name
                }
              }
            }
            departments {
              getItems {
                id
                removed
                name
                employees {
                 id
                 name
                 pinyin
                 removed
                  phoneNumber
                  officialRank
                  isMale
                  department {
                    id
                    name
                  }
                }
                getTeams {
                    id
                    name
                    getItems {
                     id
                    name
                    pinyin
                    phoneNumber
                    officialRank
                    isMale
                    removed
                    department {
                      id
                      name
                    }
                   }
                }
              }
            }
            teams {
              getItems {
                id
                name
                getItems {
                  id
                  name
                  pinyin
                  phoneNumber
                  officialRank
                  isMale
                  removed
                  department {
                    id
                    name
                  }
                }
              }
            }
          }
        }
        }`})
      // = res.data.data.organizationQueryRepository.findById.departments.getItems
      const departments = []
      res.data.data.organizationQueryRepository.findById.departments.getItems.forEach(item => {
        const children = []
        item.getTeams && item.getTeams.forEach(aItem => {
          children.push({
            name: aItem.name,
            employees: aItem.getItems
          })
        })
        departments.push({
          name: item.name,
          employees: item.employees,
          children: children
        })
      })
      this.companyData[0].children = departments
      this.departments = res.data.data.organizationQueryRepository.findById.departments.getItems
      this.companyData[0].employees = res.data.data.organizationQueryRepository.findById.employees.getItems
      this.tableData = res.data.data.organizationQueryRepository.findById.employees.getItems.map(item => {
        return {
          ...item,
          isAdmin: holdersWithEmployeeId.includes(item.id)
        }
      })
    },
    async getPermissionTreeByOwner() {
      const res = await this.$axios.post('/graphql', {
        query: `{
          permissionTreeQueryRepository {
          getPermissionTreeByOwner(owner: "organization:${this.employeeInfo.organization.id}") {
            getItems {
              id
              action
              description
              resource
              instance
               holdersWithEmployee {
                id
                name
                account {
                  id
                  displayName
                  loginCredentials {
                    id
                    identifier
                  }
                }
              }
            }
            size
          }
        }
        }`
      })
      res.data.data.permissionTreeQueryRepository.getPermissionTreeByOwner.getItems.forEach(item => {
        const idArr = item.id.split(":")
        if (idArr.includes('admin')) {
          this.holdersWithEmployee = item.holdersWithEmployee ? item.holdersWithEmployee.map(item => {
            return {
              ...item,
              account: item.account.loginCredentials[0].identifier
            }
          }) : []
        }
      })

    }
  },
  async mounted() {
    this.organization = this.employeeInfo.organization
    this.companyData.push({
      ...this.employeeInfo.organization,
      children: []
    })
    await this.getPermissionTreeByOwner()
    await this.getTableData()
    console.log( this.employeeInfo.organization)

    this.$nextTick(async () => {
      this.$refs.treeRef.setCheckedKeys([0], true)
      // 浏览器窗口大小发生变化时重新计算table的高度
      window.onresize = () => this.getTableHeight()
      this.getTableHeight()

    })
  }
}
</script>

<style scoped lang="scss">
.personnel_body {
  width: 100%;
  height: 100%;
}

.personnel_header {
  width: 100%;
  height: 88px;
  margin-bottom: 10px;
  box-sizing: border-box;
  padding: 10px 20px 15px;
  background-color: #ffffff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

  .personnel_header_title {
    width: 100%;
    height: auto;
    font-weight: 600;
    font-size: 24px;
    margin-bottom: 10px;

  }

  .personnel_header_subheading {
    width: 100%;
    height: auto;
    color: #ababab;
  }
}

.personnelList {
  width: 100%;
  height: calc(100% - 98px);
  display: flex;
  display: -webkit-flex;
  display: -moz-flex;

  .roleTree {
    width: 250px;
    flex-basis: 250px;
    flex-shrink: 0;
    box-sizing: border-box;
    padding: 10px;
    background-color: #ffffff;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    .tree_search {
      width: 100%;
      height: 35px;
    }

    .tree_body {
      width: 100%;
      box-sizing: border-box;
      padding-top: 10px;
      height: calc(100% - 35px);
      overflow: auto;
    }
  }

  .personnelList_div {
    width: calc(100% - 420px);
    flex-basis: calc(100% - 420px);
    flex-shrink: 0;
    height: 100%;
    box-sizing: border-box;
    padding-left: 10px;
    padding-right: 10px;

    .personnelList_div_body {
      width: 100%;
      height: 100%;
      box-sizing: border-box;
      padding: 10px 0 10px 15px;
      background-color: #ffffff;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    }
  }

  .operate_div {
    width: 170px;
    height: 100%;
    flex-basis: 170px;
    flex-shrink: 0;

    .operate_div_body {
      width: 100%;
      height: auto;
      box-sizing: border-box;
      padding: 10px 15px 20px;
      background-color: #ffffff;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    }
  }
}

.personnel_list_body {
  width: 100%;
  height: auto;
  display: flex;
  display: -webkit-flex;
  display: -moz-flex;

  .personnel_list_body_left {
    width: calc(100% - 30px);
    flex-basis: calc(100% - 30px);
    flex-shrink: 0;
    height: 100%;
    overflow: auto;
  }

  .personnel_list_body_right {
    width: 30px;
    flex-basis: 30px;
    flex-shrink: 0;
    height: 100%;
    display: flex;
    display: -webkit-flex;
    display: -moz-flex;
    overflow: auto;
    flex-wrap: wrap;
    //box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    .oneLetter {
      width: 30px;
      cursor: pointer;
      color: #6a6666;
      height: auto;
      display: flex;
      box-sizing: border-box;
      background-color: #FFFFFF;
      display: -webkit-flex;
      display: -moz-flex;
      align-items: center;
      justify-content: center;
      text-align: center;
      font-size: 14px;
      transition: background-color 0.5s, color 0.5s;
      -webkit-transition: background-color 0.5s, color 0.5s;

      &:hover {
        background-color: #148FFF;
        color: #FFFFFF;
      }
    }
  }
}

.personnel_list {
  width: 100%;
  height: auto;
  padding: 5px;
  display: flex;
  display: -webkit-flex;
  display: -moz-flex;
  gap: 15px;
  flex-wrap: wrap;
  box-sizing: border-box;

  .onePersonnel {
    width: 210px;
    height: 100px;
    padding: 10px;
    display: flex;
    display: -webkit-flex;
    display: -moz-flex;
    box-sizing: border-box;
    background: #ffffff;
    cursor: pointer;
    position: relative;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    transition: box-shadow 0.5s;

    &:hover {
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.3);
    }

    .onePersonnel_bg {
      width: 100%;
      height: 100%;
      top: 0;
      left: 0;
      position: absolute;
      background-color: transparent;
    }

    .onePersonnel_img {
      width: 100px;
      height: auto;
      flex-basis: 100px;
      flex-shrink: 0;
      box-sizing: border-box;
      padding-top: 10px;
      //background: #a4a4a4;

      &>img {
        width: 100%;
        height: auto;
      }
    }

    .personnel_content {
      width: 190px;
      flex-basis: 190px;
      flex-shrink: 0;
      box-sizing: border-box;
      //padding-left: 20px;
      //padding-top: 15px;

      .personnel_content_li {
        width: 100%;
        height: auto;
        overflow: hidden;
        white-space: nowrap;
        font-size: 14px;
        color: rgb(48, 49, 51);
        margin-bottom: 20px;
      }
    }
  }

  .onePersonnel_woman {
    border-top: 10px solid #6a6666;
  }

  .onePersonnel_man {
    border-top: 10px solid #6a6666;
  }
}

.parentClass {
  width: 100%;
  height: auto;
  box-sizing: border-box;
  padding: 5px 20px 5px 0;
}


.childCLass {
  width: 100%;
  height: auto;
  box-sizing: border-box;
  padding: 5px 10px 5px 10px;
  //border-bottom: 1px solid rgb(64, 158, 255);
  border-left: 1px solid #6a6666;
}

.pagination_body {
  width: 100%;
  height: 40px;
  display: flex;
  align-content: center;
  justify-content: flex-end;
}
</style>
<style lang="scss">
.personnelList {
  .el-button {
    border-radius: 0;

  }

  .el-button--primary {
    background-color: cornflowerblue;
  }

  .el-radio-button__original-radio:checked+.el-radio-button__inner {
    background-color: cornflowerblue;
  }
}

.operate {
  width: 100%;
  height: auto;

  .one_operate {
    width: 100%;
    height: 40px;
    line-height: 40px;
    text-align: center;
    font-size: 16px;
    color: #333333;
    cursor: pointer;
    margin-bottom: 10px;
    border-radius: 4px;
    border: 1px solid #eeeeee;
    transition: background-color 0.2s;
    -webkit-transition: background-color 0.2s;
    /* Safari */

    &:hover {
      background-color: cornflowerblue;
      color: #FFFFFF;
    }

    &:last-child {
      margin-bottom: 0;
    }
  }
}
</style>
